<!-- src/views/Register.vue -->
<template>
  <div class="login-container">
    <h2 class="login-title">
      <i class="fas fa-user-plus"></i> 用户注册
    </h2>
    <form @submit.prevent="handleRegister" id="register-form">
      <div class="form-group">
        <label for="reg-username">用户名</label>
        <input
          v-model="username"
          type="text"
          id="reg-username"
          placeholder="请输入用户名"
          required
        />
      </div>
      <div class="form-group">
        <label for="reg-password">密码</label>
        <input
          v-model="password"
          type="password"
          id="reg-password"
          placeholder="请输入密码"
          required
        />
      </div>
      <div class="form-group">
        <label for="reg-confirm-password">确认密码</label>
        <input
          v-model="confirmPassword"
          type="password"
          id="reg-confirm-password"
          placeholder="请再次输入密码"
          required
        />
      </div>
      <div class="form-group">
        <label for="reg-realname">真实姓名</label>
        <input
          v-model="realName"
          type="text"
          id="reg-realname"
          placeholder="请输入真实姓名"
          required
        />
      </div>
      <div class="form-group">
        <label for="reg-role">角色</label>
        <select v-model="role" id="reg-role" required>
          <option value="">请选择角色</option>
          <option value="applicant">活动申请人</option>
          <option value="department_head">部门负责人</option>
          <option value="advisor">指导老师</option>
          <option value="equipment_manager">物资管理员</option>
        </select>
      </div>
      <div class="form-group">
        <label for="reg-department">所属部门/社团</label>
        <input
          v-model="department"
          type="text"
          id="reg-department"
          placeholder="请输入所属部门或社团"
        />
      </div>
      <button type="submit" class="btn">注册</button>
    </form>
    <p>
      已有账号？<a href="#" @click.prevent="goToLogin">立即登录</a>
    </p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const realName = ref('')
const role = ref('')
const department = ref('')
const router = useRouter()

const handleRegister = async () => {
  // 前端必填校验
  if (!username.value || !password.value || !confirmPassword.value || !realName.value || !role.value) {
    alert('请填写所有必填字段！')
    return
  }

  // 密码一致性校验
  if (password.value !== confirmPassword.value) {
    alert('两次输入的密码不一致！')
    return
  }

  try {
    // 发送注册请求
    const response = await axios.post('http://localhost:8080/api/v1/user/logon', {
      username: username.value,
      password: password.value,
      realName: realName.value,
      role: role.value,
      department: department.value
    })

    const resp = response.data // Response<String>

// 在 Register.vue 的 handleRegister 中
    if (String(resp.code) === '0000') {
      alert(`✅ 注册成功！\n\n${resp.data || ''}`)
      router.push('/login')
    } else {
      alert(`❌ 注册失败\nCode: ${resp.code}\nInfo: ${resp.info}`)
    }
  } catch (error) {
    console.error('注册请求失败:', error)
    if (error.response) {
      // 后端返回了错误响应体（如 400, 500）
      const errMsg = error.response.data?.info || '服务器处理失败'
      alert('注册失败：' + errMsg)
    } else if (error.request) {
      // 请求已发出但无响应（如后端未启动）
      alert('无法连接到后端服务，请确保 Spring Boot 应用已启动（端口 8080）')
    } else {
      // 请求配置错误（如 URL 写错）
      alert('请求出错：' + error.message)
    }
  }
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #1e88e5;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
}

input,
select,
textarea {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.btn {
  display: inline-block;
  background: #1e88e5;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  transition: background 0.3s;
  width: 100%;
}

.btn:hover {
  background: #1565c0;
}

p {
  text-align: center;
  margin-top: 20px;
}

p a {
  color: #1e88e5;
  text-decoration: none;
}

p a:hover {
  text-decoration: underline;
}
</style>
